const fs = require("fs");
const path = require("path");

// 读取文件
export function readFile(fileName) {
  const filepath = path.join(__dirname, `./database/${fileName}.json`);
  const rawData = fs.readFileSync(filepath, "utf8");
  return JSON.parse(rawData);
}

// 写入文件
export function writeFile(fileName, value) {
  // 转为json
  value = JSON.stringify(value, null, 2);
  // 写入
  const filepath = path.join(__dirname, `./database/${fileName}.json`);
  fs.writeFileSync(filepath, value);
}

// 查找一个
export function findOne(fileName, value, key = "id") {
  const { data } = readFile(fileName);
  return data.filter((item) => item[key] == value)[0];
}

// 查询全部
export function getAll(fileName) {
  const { data } = readFile(fileName);
  return data;
}

function filterInvalidKey(object) {
  for (const key in object) {
    if (Object.prototype.toString.call(object[key]) === "[object Object]") {
      filterInvalidKey(object[key]);
    } else if (Array.isArray(object[key]) && !object[key].length) {
      delete object[key];
    } else {
      if (!object[key] && object[key] !== 0 && object[key] !== false) {
        delete object[key];
      }
    }
  }
  return object;
}

// 分页、条件查询列表
export function getList(fileName, params = {}) {
  const { data } = readFile(fileName);
  const { pageNum, pageSize, ...filters } = params;
  let list = data,
    start,
    end;
  // 条件查询
  const obj = filterInvalidKey(filters) || {};
  const keys = Object.keys(obj);
  if (keys.length) {
    list = list.filter((item) => {
      const arr = keys.map((key) => {
        if (item[key] && item[key].includes(obj[key])) {
          return true;
        }
        return false;
      });
      return arr.every((flag) => flag);
    });
  }
  if (!pageNum || !pageSize) {
    return list;
  }
  // 分页查询
  start = (pageNum - 1) * pageSize;
  end = start + pageSize;
  list = list.slice(start, end);
  return list;
}

export function addData(fileName, newData) {
  let { data } = readFile(fileName);
  const lastChild = data[data.length - 1];
  // 生成id
  const id = lastChild.id + 1;
  newData = {
    ...newData,
    id,
    createTime: Date.now(),
  };
  data.push(newData);
  writeFile(fileName, { data });
  return newData;
}

export function updateData(fileName, newData, key = "id") {
  let { data } = readFile(fileName);
  const index = data.findIndex((item) => item[key] == newData[key]);
  newData = {
    ...newData,
    updateTime: Date.now(),
  };
  data[index] = newData;
  writeFile(fileName, { data });
  return newData;
}

export function deleteData(fileName, value, key = "id") {
  let { data } = readFile(fileName);
  const index = data.findIndex((item) => item[key] == value);
  if (index === -1) {
    return false;
  }
  data.splice(index, 1);
  writeFile(fileName, { data });
  return true;
}
